<template>
  <BasicModal 
    v-bind="$attrs" 
    @register="registerModal" 
    :title="getTitle" 
    width="650px" 
    @ok="handleSubmit" 
    @cancel="handleClose"
    showFooter
    destroyOnClose
  >
    <BasicForm @register="registerForm"/>
    <div style="height: 50px;"></div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs, onMounted, onUnmounted } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { applyInputFormSchemas, SubjectType } from './data';
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { savePermissionApply , getPermissionApply, listMenuResourceByUrl } from '/@/api/sys/ram';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from "/@/store/modules/user"
  import * as TenantApi from '/@/api/sys/tenant'
  import * as RoleApi from '/@/api/sys/role'
  import { eachTree } from "/@/utils/helper/treeHelper"
  import pubsub from "pubsub-js"
  import { useRouter } from "vue-router"
  const router = useRouter()
  const userStore = useUserStore()
  const { createMessage } = useMessage();
  const emit = defineEmits(['close', 'success', 'register']);
  const attrs = useAttrs()
  const isUpdate = ref(true);
  const record = ref<any>({});
  const applyUrls = ref<string[]>([])

  const [registerForm, {getFieldsValue, resetFields, setFieldsValue, validate, updateSchema}] = useForm({
    labelWidth: 90,
    schemas: applyInputFormSchemas,
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, md: 24 },
  });

  onMounted(() => {
    // 添加权限申请, 避免同时请求多个接口多次弹窗
    pubsub.subscribe("addPermApply", async (msg, data) => {
      console.log('subscribe-addPermApply: ', data)
      if (!data.url || applyUrls.value.includes(data.url)) {
        return
      }
      
      applyUrls.value = Array.from(new Set([...applyUrls.value, data.url]))
      const addResourceIds = await listMenuResourceByUrl({ urls: [data.url] })
      const oldResourceIds = await getFieldsValue().resourceIds || []
      setFieldsValue({ resourceIds: Array.from(new Set([...oldResourceIds, ...addResourceIds]))})
    })
  })

  onUnmounted(() => {
    pubsub.unsubscribe("addPermApply")
  })
  
  const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
    await resetFields();
    setModalProps({ confirmLoading: false, loading: true, canFullscreen: false })
    try {
      isUpdate.value = !!data?.isUpdate;
      const apiResourceUrls = data.record?.apiResourceUrls
      let initResource : any[] = []
      let initResourceIds : any[] = []
      applyUrls.value = Array.from(new Set([...applyUrls.value, ...apiResourceUrls]))
      if (applyUrls.value.length > 0) {
        initResource = await listMenuResourceByUrl({ urls: applyUrls.value, pageUrl: router.currentRoute.value.path })
      }

      record.value = data.record
   
      if (unref(isUpdate)) {
        record.value = await getPermissionApply({id: data.record.id}) || {} 
      }

      const menuTreeData = await TenantApi.listCurrentPackageMenuTree()
      if (initResource && initResource.length > 0) {
        let isExistMenu = false
        initResourceIds = initResource.map(e=> e.id)
        eachTree(menuTreeData, (item, _parent) => {
          if (isExistMenu) return
          isExistMenu = initResourceIds.indexOf(item.id) != -1
        })
        if (!isExistMenu) {
          const apiActions = initResource.map(e=> e.action).join('|')
          createMessage.error('租户套餐不包含该资源[' + apiActions + ']')
          throw new Error('资源不存在')
        }
      }
  
      updateSchema([
        {
          field: "resourceIds",
          componentProps: {
            treeData: menuTreeData, 
            immediate: true
          },
        },
        // 主体类型
        {
          field: "subjectType",
          componentProps: {
            type: "radio",
            dictType: 'ramSubjectType',
            onChange: (value: any) => {
              console.log("option", value)
              if (SubjectType.USER == value) {
                return
              }
              updateSchema([
                {
                  field: "subjectId",
                  componentProps: {
                    api: RoleApi.listRoleByUserId,
                    optionFilterProp: "label",
                    showSearch: true,
                    labelField: "roleName",
                    valueField: "id",
                    params: {
                      userId: userStore.getUserInfo.id
                    },
                  },
                }
              ])

              setFieldsValue({ parentId: null })
            }
          }
        }
      ])


      setFieldsValue({ 
        applyUserName: userStore.getUserInfo.userName,
        // 用户主体名称
        userSubjectName: userStore.getUserInfo.userName,
        applyTenantName: userStore?.getSelectTenant?.name,
        ...record.value,
        resourceIds: record.value?.resourceIds || initResourceIds
      })

    } catch(e) {
      emit('close')
      closeModal()
    } finally {
      setModalProps({ loading: false })
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增权限申请' : '编辑权限申请'));

  async function handleSubmit() {
    try {
      let values = await validate();
      setModalProps({confirmLoading: true});

      await savePermissionApply({ ...values, resourceIds: values.resourceIds.split(',') });
      closeModal();
      createMessage.success(`${getTitle.value}成功`)
      emit('success');
    } finally {
      setModalProps({confirmLoading: false});
    }
  }

  const handleClose = () => emit('close')
</script>
